<template>
  <div class="app-container">
    <el-form ref="form" :model="mock_data" label-width="120px">
      <el-form-item label="Mock名称" required>
        <el-input v-model="mock_data.name" style="width: 46%" />
      </el-form-item>
      <el-form-item label="接口信息" required>
        <el-row>
          <el-col :span="11">
            <el-input
              v-model="mock_data.mock_url"
              placeholder="请输入mock url地址, 例如：v1/test, 前面不要加/"
              @keyup.native="mock_data.mock_url=mock_data.mock_url.replace(/^[\/]*/g,'')"
            >
              <template slot="prepend">URL</template>
            </el-input>
          </el-col>
          <el-col :span="1">
            <el-tooltip class="item" effect="dark">
              <div slot="content">
                mock接口调用方式：http://后台域名或IP:端口/mock/配置中的url路径<br>
              </div>
              <i class="el-icon-info" style="font-size: 20px; font-weight: 500; top: 50%" />
            </el-tooltip>
          </el-col>
          <el-col :span="2">
            <el-select
              ref="request_method"
              v-model="mock_data.request_method"
              placeholder="Select Method"
              @change="methodChange"
            >
              <el-option label="POST" value="POST" />
              <el-option label="GET" value="GET" />
            </el-select>
          </el-col>
          <el-col :span="2">
            <el-select
              ref="request_method_get"
              v-model="mock_data.request.request.type"
              placeholder="Select Data type"
              @change="typeChange"
            >
              <el-option v-if="mock_data.request_method === 'GET'" label="params" value="params" />
              <el-option v-if="mock_data.request_method === 'POST'" label="data" value="data" />
              <el-option v-if="mock_data.request_method === 'POST'" label="json" value="json" />
            </el-select>
          </el-col>
        </el-row>

        <div v-if="mock_data.request.request.type === 'params'" key="params" style="margin-top: 15px">
          <tableSelect
            v-if="getinfo_flag || !operation_type"
            ref="TableSelectParams"
            :table-type="'Params'"
            :datas-text.sync="mock_data.request.request.content"
            @changeList="changeParamsLists"
          />
        </div>
        <div v-else-if="mock_data.request.request.type === 'data'" key="data" style="margin-top: 15px">
          <tableSelect
            v-if="getinfo_flag || !operation_type"
            ref="TableSelectData"
            :table-type="'Data'"
            :datas-text.sync="mock_data.request.request.content"
            @changeList="changeDataLists"
          />
        </div>
        <div v-else style="margin-top: 15px">
          <div v-if="getinfo_flag || !operation_type">
            <b-code-editor
              ref="editor"
              v-model="mock_data.request.request.content"
              theme="rubyblue"
              :auto-format="true"
              :indent-unit="4"
              :smart-indent="true"
              :line-wrap="true"
            />
          </div>
          <el-button
            type="success"
            @click="$refs['editor'].formatCode()"
          >格式化JSON
          </el-button>
          <el-button
            type="success"
            @click="validateJSON"
          >校验JSON
          </el-button>
        </div>

        <tableSelect
          v-if="getinfo_flag || !operation_type"
          ref="TableSelectHeaders"
          :table-type="'Headers'"
          :datas-text.sync="mock_data.request.request.headers"
          style="margin-top: 15px"
          @changeList="changeHeadersLists"
        />
      </el-form-item>
      <el-form-item label="Response" required>
        <div v-if="getinfo_flag || !operation_type">
          <b-code-editor
            ref="response_editor"
            v-model="mock_data.response_body"
            :auto-format="true"
            :indent-unit="4"
            :smart-indent="true"
            :line-wrap="true"
            theme="dracula"
          />
        </div>
        <el-button
          type="success"
          @click="$refs['response_editor'].formatCode()"
        >格式化JSON
        </el-button>
        <el-button
          type="success"
          @click="responseValidateJSON"
        >校验JSON
        </el-button>
      </el-form-item>
      <el-form-item>
        <div style="text-align: center">
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="onCancel">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import tableSelect from '@/components/tableSelect'
import { createMock, getMock, updateMock } from '@/api/mock/table'

const jsonData = '{"key": "value"}'

export default {
  components: {
    tableSelect
  },

  data() {
    return {
      operation_type: 0, // 0:create 1:update 2:copy
      mockID: '',
      getinfo_flag: false,
      mock_data: {
        name: '',
        mock_url: '',
        request_method: 'POST',
        author: '',
        response_body: jsonData,
        request: {
          request: {
            type: 'data',
            content: [],
            headers: []
          }
        }
      }
    }
  },

  created() {
    this.operation_type = this.$route.query.operation_type || 0
    this.mockID = this.$route.query.id || ''
    if (this.operation_type !== 0) {
      this.getData() // 编辑或复制
    }
  },

  methods: {
    onSubmit() {
      if (this.operation_type.toString() === '1') {
        updateMock(this.mock_data).then(response => {
          if (response.status === '000000') return
          this.$message.success('更新成功')
          this.$router.replace(`/mock/mock_list`)
        })
      } else {
        createMock(this.mock_data).then((response) => {
          console.log(response.msg)
          if (response.status === '000000') return
          this.$message.success('创建成功')
          this.$router.replace(`/mock/mock_list`)
        })
      }
    },

    onCancel() {
      this.$confirm('此操作将退出编辑, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.replace(`/mock/mock_list`)
        this.$message({
          type: 'success',
          message: '退出成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出'
        })
      })
    },
    getMockData() {
      var params = {}
      params['id'] = this.mockID
      return new Promise((resolve, reject) => {
        getMock(params).then(response => {
          this.mock_data = response.data
          this.getinfo_flag = response.success
          resolve(response)
        }).catch(e => {
          reject(e)
        })
      })
    },
    async getData() {
      await this.getMockData()
    },

    validateJSON() {
      if (this.mock_data.request.request.type === 'json') {
        var str = this.mock_data.request.request.content
        if (typeof str === 'string') {
          try {
            var obj = JSON.parse(str)
            if (typeof obj === 'object' && obj) {
              this.$message.info(`json格式正确`)
              return true
            } else {
              this.$message.error(`json格式错误,请修正后再提交`)
              return false
            }
          } catch (e) {
            this.$message.error(`json格式错误,请修正后再提交`)
            return false
          }
        } else if (typeof str === 'object' && str) {
          this.$message.error(`json格式错误,请修正后再提交`)
          return true
        }
      }
    },

    responseValidateJSON() {
      var str = this.mock_data.response_body
      if (typeof str === 'string') {
        try {
          var obj = JSON.parse(str)
          if (typeof obj === 'object' && obj) {
            this.$message.info(`json格式正确`)
            return true
          } else {
            this.$message.error(`json格式错误,请修正后再提交`)
            return false
          }
        } catch (e) {
          this.$message.error(`json格式错误,请修正后再提交`)
          return false
        }
      } else if (typeof str === 'object' && str) {
        this.$message.error(`json格式错误,请修正后再提交`)
        return true
      }
    },

    methodChange() {
      console.log('Request Method : ' + this.mock_data.request_method)
      if (this.mock_data.request_method === 'GET') {
        this.$set(this.mock_data.request.request, 'type', 'params')
      }
      if (this.mock_data.request_method === 'POST') {
        this.$set(this.mock_data.request.request, 'type', 'data')
      }
    },

    typeChange() {
      console.log('Request Type : ' + this.mock_data.request.request.type)
      if (this.mock_data.request.request.type === 'json') {
        console.log('Request content : ' + this.mock_data.request.request)
        // this.form.request.request.push({'json': jsonData})
        this.mock_data.request.request.content = jsonData
      }
      if (this.mock_data.request.request.type === 'data') {
        // this.form.request.request.push({'data': []})
        this.mock_data.request.request.content = []
      }
      if (this.mock_data.request.request.type === 'params') {
        // this.form.request.request.push({'params': []})
        this.mock_data.request.request.content = []
      }
    },

    changeDataLists: function(obj) {
      this.mock_data.request.request.content = obj.list
    },
    changeParamsLists: function(obj) {
      this.mock_data.request.request.content = obj.list
    },
    changeHeadersLists: function(obj) {
      this.mock_data.request.request.headers = obj.list
    }
  }
}
</script>

<style scoped>
.line{
  text-align: center;
}
</style>

